package com.qiu.greened.ui.main

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.qiu.greened.adapter.NotificationsReplyAdapter
import com.qiu.greened.databinding.FragmentNotificationsBinding
import com.qiu.greened.utils.showToast
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class NotificationsFragment : Fragment() {

    private val viewModel: NotificationsViewModel by viewModels()
    private var _binding: FragmentNotificationsBinding? = null
    private val binding get() = _binding!!
    private val replyAdapter by lazy { NotificationsReplyAdapter() }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentNotificationsBinding.inflate(inflater, container, false)
        setReplyData()
        return binding.root
    }

    private fun setReplyData() {
        val linearLayoutManager = LinearLayoutManager(context)
        binding.recyclerView.layoutManager = linearLayoutManager
        binding.recyclerView.adapter = replyAdapter
        binding.recyclerView.addItemDecoration(
            DividerItemDecoration(context, DividerItemDecoration.VERTICAL)
        )
        lifecycleScope.launch {
            viewModel.getPagingData().collect { pagingData ->
                replyAdapter.submitData(pagingData)
            }
        }
        replyAdapter.addLoadStateListener {
            when (it.refresh) {
                is LoadState.NotLoading -> {
                    binding.recyclerView.visibility = View.VISIBLE
                }
                is LoadState.Loading -> {
                    binding.recyclerView.visibility = View.INVISIBLE
                }
                is LoadState.Error -> {
                    val state = it.refresh as LoadState.Error
                    "Load Error: ${state.error.message}".showToast()
                }
            }
        }
        replyAdapter.addOnPagesUpdatedListener {
            binding.recyclerView.scrollToPosition(0)
        }
    }

    override fun onResume() {
        super.onResume()
        activity?.title = "通知"
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}